<?php

/*
Plugin Name: Kimili Flash Embed
Plugin URI: http://www.kimili.com/plugins/kml_flashembed
Description: Provides a wordpress interface for Geoff Stearns' excellent standards compliant <a href="http://blog.deconcept.com/flashobject/">Flash detection and embedding JavaScript</a>. The syntax is <code>[kml_flashembed movie=&quot;filename.swf&quot; height=&quot;250&quot; width=&quot;400&quot; /]</code>.
Version: 1.1b
Author: Michael Bester
Author URI: http://www.kimili.com
Update: http://www.kimili.com/plugins/wp
*/

/*
*
*	KIMILI FLASH EMBED
*
*	Copyright 2006 Michael Bester (http://www.kimili.com)
*	Released under the terms of the BSD License (http://www.opensource.org/licenses/bsd-license.php)
*
*/	

// Thanks to Jeff Minard ( http://www.thecodepro.com/ ) for showing me how to embed the JS directly in the plugin.

// 2006-12-11 - Albert Lash ( http://www.docunext.com/ ) added code to 
// return 304 Not modified header, which enables browser-side caching, greatly speeding up page renderings
// Also changed test to determine output from a get variable to a request_uri test, improving the chances of
// the content getting cached. 
// I think this should probably be used instead at some point. 
// Also added gzip handler and buffer for what its worth. 


$mynid = $_SERVER['SCRIPT_FILENAME'];

if( stristr($_SERVER['REQUEST_URI'], 'kml_flashembed.php') && !stristr($_SERVER['REQUEST_URI'], 'wp-admin')) {

ob_start();
ob_start('ob_gzhandler');

$last_modified_str = filemtime($mynid);
$file_size = filesize($mynid);
$etag = md5($last_modified_str);
$last_modified = gmdate('D, d M Y H:i:s', $last_modified_str);

$request = getallheaders();
if (isset($request['If-Modified-Since'])) {
   $modifiedSince = explode(';', $request['If-Modified-Since']);
   $modifiedSince = strtotime($modifiedSince[0]);
} else {
   $modifiedSince = 0;
}
if ($last_modified_str <= $modifiedSince) {
        while (@ob_end_clean());                                            
        header("HTTP/1.0 304 Not Modified");
        exit;
}
// Expires in seven days from access time.
$offset = 7 * 86400;
$ExpStr = "Expires: " . gmdate("D, d M Y H:i:s", time() + $offset) . " GMT";
header($ExpStr);
header("ETag: $etag");
header('Last-Modified: '.$last_modified . ' GMT');

	header('Content-type: text/javascript');
	?>
/**
 * FlashObject v1.3d: Flash detection and embed - http://blog.deconcept.com/flashobject/
 *
 * FlashObject is (c) 2006 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
if(typeof com=="undefined"){var com=new Object();}
if(typeof com.deconcept=="undefined"){com.deconcept=new Object();}
if(typeof com.deconcept.util=="undefined"){com.deconcept.util=new Object();}
if(typeof com.deconcept.FlashObjectUtil=="undefined"){com.deconcept.FlashObjectUtil=new Object();}
com.deconcept.FlashObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a,_b){
if(!document.createElement||!document.getElementById){return;}
this.DETECT_KEY=_b?_b:"detectflash";
this.skipDetect=com.deconcept.util.getRequestParameter(this.DETECT_KEY);
this.params=new Object();
this.variables=new Object();
this.attributes=new Array();
this.useExpressInstall=_7;
if(_1){this.setAttribute("swf",_1);}
if(id){this.setAttribute("id",id);}
if(w){this.setAttribute("width",w);}
if(h){this.setAttribute("height",h);}
if(_5){this.setAttribute("version",new com.deconcept.PlayerVersion(_5.toString().split(".")));}
this.installedVer=com.deconcept.FlashObjectUtil.getPlayerVersion(this.getAttribute("version"),_7);
if(c){this.addParam("bgcolor",c);}
var q=_8?_8:"high";
this.addParam("quality",q);
var _d=(_9)?_9:window.location;
this.setAttribute("xiRedirectUrl",_d);
this.setAttribute("redirectUrl","");
if(_a){this.setAttribute("redirectUrl",_a);}
};
com.deconcept.FlashObject.prototype={setAttribute:function(_e,_f){
this.attributes[_e]=_f;
},getAttribute:function(_10){
return this.attributes[_10];
},addParam:function(_11,_12){
this.params[_11]=_12;
},getParams:function(){
return this.params;
},addVariable:function(_13,_14){
this.variables[_13]=_14;
},getVariable:function(_15){
return this.variables[_15];
},getVariables:function(){
return this.variables;
},createParamTag:function(n,v){
var p=document.createElement("param");
p.setAttribute("name",n);
p.setAttribute("value",v);
return p;
},getVariablePairs:function(){
var _19=new Array();
var key;
var _1b=this.getVariables();
for(key in _1b){_19.push(key+"="+_1b[key]);}
return _19;
},getFlashHTML:function(){
var _1c="";
if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){
if(this.getAttribute("doExpressInstall")){
this.addVariable("MMplayerType","PlugIn");
}
_1c="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\"";
_1c+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";
var _1d=this.getParams();
for(var key in _1d){_1c+=[key]+"=\""+_1d[key]+"\" ";}
var _1f=this.getVariablePairs().join("&");
if(_1f.length>0){_1c+="flashvars=\""+_1f+"\"";}
_1c+="/>";
}else{
if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");}
_1c="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\">";
_1c+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";
var _20=this.getParams();
for(var key in _20){_1c+="<param name=\""+key+"\" value=\""+_20[key]+"\" />";}
var _22=this.getVariablePairs().join("&");
if(_22.length>0){_1c+="<param name=\"flashvars\" value=\""+_22+"\" />";
}_1c+="</object>";}
return _1c;
},write:function(_23){
if(this.useExpressInstall){
var _24=new com.deconcept.PlayerVersion([6,0,65]);
if(this.installedVer.versionIsValid(_24)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){
this.setAttribute("doExpressInstall",true);
this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));
document.title=document.title.slice(0,47)+" - Flash Player Installation";
this.addVariable("MMdoctitle",document.title);}
}else{this.setAttribute("doExpressInstall",false);}
if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){
var n=(typeof _23=="string")?document.getElementById(_23):_23;
n.innerHTML=this.getFlashHTML();
}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}}};
com.deconcept.FlashObjectUtil.getPlayerVersion=function(_26,_27){
var _28=new com.deconcept.PlayerVersion(0,0,0);
if(navigator.plugins&&navigator.mimeTypes.length){
var x=navigator.plugins["Shockwave Flash"];
if(x&&x.description){_28=new com.deconcept.PlayerVersion(x.description.replace(/([a-z]|[A-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}
}else{
try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
for(var i=3;axo!=null;i++){
axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+i);
_28=new com.deconcept.PlayerVersion([i,0,0]);}}
catch(e){}
if(_26&&_28.major>_26.major){return _28;}
if(!_26||((_26.minor!=0||_26.rev!=0)&&_28.major==_26.major)||_28.major!=6||_27){
try{
_28=new com.deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));
}catch(e){}}}
return _28;
};
com.deconcept.PlayerVersion=function(_2c){
this.major=parseInt(_2c[0])||0;
this.minor=parseInt(_2c[1])||0;
this.rev=parseInt(_2c[2])||0;
};
com.deconcept.PlayerVersion.prototype.versionIsValid=function(fv){
if(this.major<fv.major){return false;}
if(this.major>fv.major){return true;}
if(this.minor<fv.minor){return false;}
if(this.minor>fv.minor){return true;}
if(this.rev<fv.rev){return false;}
return true;
};
com.deconcept.util={getRequestParameter:function(_2e){
var q=document.location.search||document.location.hash;
if(q){var _30=q.indexOf(_2e+"=");
var _31=(q.indexOf("&",_30)>-1)?q.indexOf("&",_30):q.length;
if(q.length>1&&_30>-1){
return q.substring(q.indexOf("=",_30)+1,_31);}}return "";
},removeChildren:function(n){
while(n.hasChildNodes()){
n.removeChild(n.firstChild);}}};
if(Array.prototype.push==null){
Array.prototype.push=function(_33){
this[this.length]=_33;
return this.length;};}
var getQueryParamValue=com.deconcept.util.getRequestParameter;
var FlashObject=com.deconcept.FlashObject;
<?php 
	ob_end_flush();
	
	
	header("Content-Length: ".ob_get_length());
	ob_end_flush();

die(); }

/***********************************************************************
*	Global Vars
************************************************************************/

$kml_request_type	= "";
$kml_flashembed_ver	= "1.1";


/***********************************************************************
*	Apply the filter 
************************************************************************/

if (preg_match("/(\/\?feed=|\/feed)/i",$_SERVER['REQUEST_URI'])) {
	// RSS Feeds
	$kml_request_type	= "feed";
} else {
	// Everything else
	$kml_request_type	= "nonfeed";
	add_action('wp_head', 'kml_add_flashobject_js');
	//add_action('wp_footer', 'kml_add_flashobject_js');
}

// Apply all over except the admin section
if (strpos($_SERVER['REQUEST_URI'], 'wp-admin') === false ) {

	add_filter('the_content','kml_flashembed');
	ob_start();
}


/***********************************************************************
*	Run the main function 
************************************************************************/

function kml_flashembed($content) {
	$pattern = '/([\[<]KML_FLASHEMBED.*\/[\]>])|([\[<]KML_FLASHEMBED.*[\]>][\[<]\/KML_FLASHEMBED[\]>])/Ui'; 
	$result = preg_replace_callback($pattern,'kml_parse_kfe_tags',$content);
	return $result;	
}


/***********************************************************************
*	Parse out the KFE Tags
************************************************************************/

function kml_parse_kfe_tags($match) {
	
	$r	= "";
			
	# Clean up and untexturize tag
	$strip		= array('[KML_FLASHEMBED',
						'][/KML_FLASHEMBED]',
						'[kml_flashembed',
						'][/kml_flashembed]',
						'/]',
						'<KML_FLASHEMBED',
						'></KML_FLASHEMBED>',
						'<kml_flashembed',
						'></kml_flashembed>',
						'/>',
						'\n',
						'<br>',
						'<br />'
						);
						
	$elements	= str_replace($strip, '', $match[0]);
	
	$elements	= preg_replace("/=(\s*)\"/", "==`", $elements);
	$elements	= preg_replace("/=(\s*)&Prime;/", "==`", $elements);
	$elements	= preg_replace("/=(\s*)&prime;/", "==`", $elements);
	$elements	= preg_replace("/=(\s*)&#8221;/", "==`", $elements);
	$elements	= preg_replace("/\"(\s*)/", "`| ", $elements);
	$elements	= preg_replace("/&Prime;(\s*)/", "`|", $elements);
	$elements	= preg_replace("/&prime;(\s*)/", "`|", $elements);
	$elements	= preg_replace("/&#8221;(\s*)/", "`|", $elements);
	$elements	= preg_replace("/&#8243;(\s*)/", "`|", $elements);
	$elements	= preg_replace("/&#8216;(\s*)/", "'", $elements);
	$elements	= preg_replace("/&#8217;(\s*)/", "'", $elements);
	
	$attpairs	= preg_split('/\|/', $elements, -1, PREG_SPLIT_NO_EMPTY);
	$atts		= array();
	
	// Create an associative array of the attributes
	for ($x = 0; $x < count($attpairs); $x++) {
		
		$attpair		= explode('==', $attpairs[$x]);
		$attn			= trim(strtolower($attpair[0]));
		$attv			= preg_replace("/`/", "", trim($attpair[1]));
		$atts[$attn]	= $attv;
	}
	
	if (!empty($atts['movie']) && !empty($atts['height']) && !empty($atts['width'])) {
		
		$atts['fversion'] 			= (!empty($atts['fversion'])) ? $atts['fversion'] : 6;
		$atts['height']				= ($height{strlen($atts['height']) - 1} == "%") ? '"' . $atts['height'] . '"' : $atts['height'];
		$atts['width']				= ($width{strlen($atts['width']) - 1} == "%") ? '"' . $atts['width'] . '"' : $atts['width'];
		$atts['useexpressinstall']	= (!empty($atts['useexpressinstall'])) ? $atts['useexpressinstall'] : '""';
		$atts['detectKey']			= (!empty($atts['detectKey'])) ? ',"' . $atts['detectKey'] . '"' : '';
		
		$fvarpair_regex		= "/(?<!([$|\?]\{))\s+;\s+(?!\})/";
		$atts['fvars']		= (!empty($atts['fvars'])) ? preg_split($fvarpair_regex, $atts['fvars'], -1, PREG_SPLIT_NO_EMPTY) : array();
		
		// Convert any quasi-HTML in alttext back into tags
		$atts['alttext']	= (!empty($atts['alttext'])) ? preg_replace("/{(.*?)}/i", "<$1>", $atts['alttext']) : "" ;
		
		// If we're not serving up a feed, generate the script tags
		if ($GLOBALS['kml_request_type'] != "feed") {
			$r	= kml_build_fo_script($atts);
		}
	}
 	return $r; 
}


/***********************************************************************
*	Build the Javascript from the tags
************************************************************************/

function kml_build_fo_script($atts) {
	
	$out	= array();	
	if (is_array($atts)) extract($atts);
	
	// Extract the filename minus the extension...
	$swfname			= (strrpos($movie, "/") === false) ?
							$movie :
							substr($movie, strrpos($movie, "/") + 1, strlen($movie));
	$swfname			= (strrpos($swfname, ".") === false) ?
							$swfname :
							substr($swfname, 0, strrpos($swfname, "."));
	
	// ... to use as a default ID if an ID is not defined.
	$id			= (!empty($id)) ? $id : "fm_" . $swfname;
	// ... as well as an empty target if that isn't defined.
	if (empty($target)) {
		$rand		= mt_rand();
		$targname	= "fo_targ_" . $swfname . $rand;
		// Create a target div
		$out[]		= '<div id="' . $targname . '">'.$alttext.'</div>';
		$target	= $targname;
	}				
	$GLOBALS['target'] = $target;
	
									$out[] = '';
						  	  		$out[] = '<script type="text/javascript">';
						  	  		$out[] = '	// <![CDATA[';
									$out[] = '';
						  	  		$out[] = '	var flashObject = new FlashObject("' . $movie . '","' . $id . '","' . $width . '","' . $height . '","' . $fversion . '","' . $bgcolor . '",' . $useexpressinstall . ',"' . $quality . '","' . $xiredirecturl . '","' . $redirecturl . '"' . $detectKey . ');';
	if (!empty($play))				$out[] = '	flashObject.addParam("play", "' . $play . '");';
	if (!empty($loop))				$out[] = '	flashObject.addParam("loop", "' . $loop . '");';
	if (!empty($menu)) 				$out[] = '	flashObject.addParam("menu", "' . $menu . '");';
	if (!empty($scale)) 			$out[] = '	flashObject.addParam("scale", "' . $scale . '");';
	if (!empty($wmode)) 			$out[] = '	flashObject.addParam("wmode", "' . $wmode . '");';
	if (!empty($align)) 			$out[] = '	flashObject.addParam("align", "' . $align . '");';
	if (!empty($salign)) 			$out[] = '	flashObject.addParam("salign", "' . $salign . '");';
	if (!empty($allowscriptaccess))	$out[] = '	flashObject.addParam("AllowScriptAccess", "' . $allowscriptaccess . '");';
	if (!empty($base))				$out[] = '	flashObject.addParam("base", "' . $base . '");';
	// Loop through and add any name/value pairs in the $fvars attribute
	for ($i = 0; $i < count($fvars); $i++) {
		$thispair	= trim($fvars[$i]);
		$nvpair		= explode("=",$thispair);
		$name		= trim($nvpair[0]);
		$value		= trim($nvpair[1]);
		// Prune out JS or PHP values
		if (preg_match("/^\\$\\{.*\\}/i", $value)) { 		// JS
			$endtrim 	= strlen($value) - 3;
			$value		= substr($value, 2, $endtrim);
			$value		= str_replace(';', '', $value);
		} else if (preg_match("/^\\?\\{.*\\}/i", $value)) {	// PHP
			$endtrim 	= strlen($value) - 3;
			$value 		= substr($value, 2, $endtrim);
			$value 		= '"'.eval("return " . $value).'"';
		} else {
			$value = '"'.$value.'"';
		}
									$out[] = '	flashObject.addVariable("' . $name . '",' . $value . ');';
	}
	
									//$out[] = '	flashObject.write("' . $target . '");';
									$out[] = '';
									$out[] = '	// ]]>';
									$out[] = '</script>';
	// Add NoScript content
	if (!empty($noscript)) {
									$out[] = '<noscript>';
									$out[] = '	' . $noscript;
									$out[] = '</noscript>';
	}
									$out[] = '';
											
	$ret .= join("\n", $out);
	return $ret;
}


/***********************************************************************
*	Add the call to flashobject.js
************************************************************************/

function kml_add_flashobject_js() {
	global $kml_flashembed_ver;

	echo '
	<!-- Courtesy of Kimili Flash Embed - Version '. $kml_flashembed_ver .' -->
	<script src="' . get_bloginfo('wpurl') . '/wp-content/plugins/kml_flashembed.php" type="text/javascript" defer="defer"></script>
';

}

function kml_write_flashobject($atts) { 

//	if (is_array($atts)) extract($atts);
	$target = $GLOBALS['target'];

	echo "
	<script type='text/javascript' defer='defer'>
		flashObject.write('" . $target . "');
	</script>";

}

add_action("wp_footer","kml_write_flashobject",5);

?>
